<template>
  <div class="content">
    <div v-if="buyStatus==='' || buyStatus==='NORMAL'">
      <!-- 类型 -->
      <el-row>
        <h3>请选择类型</h3>
        <div>
          <el-radio v-model="ticketType" label="year" border @change="ticketTypeChange">年票</el-radio>
          <el-radio v-model="ticketType" label="season" border @change="ticketTypeChange">季票</el-radio>
        </div>
      </el-row>
      <!-- 旅客票价 -->
      <el-row v-if="ticketType!==null">
        <h3>旅客票价</h3>
        <div style="min-width:1366px">
          <el-card v-for="(item,index) in ticketList" :key="index" shadow="hover" class="box-card">
            <div slot="header" class="clearfix">
              <span>{{ item.description }}</span>
            </div>
            <div
              class="drop"
              style="color:#393939"
            >{{ '年龄：' + item.personTypeMinAge+' ~ '+item.personTypeMaxAge+' 岁' }}</div>
            <div class="drop" style="color:#409EFF">{{ '票价：￥ ' + item.baseProduct.prices[0].value }}</div>
            <div
              class="drop"
              style="color:#42B983"
            >{{ '余票：' + item.baseProduct.stocks[0].stock +' 张' }}</div>
          </el-card>
        </div>
      </el-row>
      <!-- 旅客信息 -->
      <el-row v-if="ticketType!==null">
        <h3>请输入旅客信息</h3>
        <div class="text_item">
          <el-row v-for="(item,index) in rowLsit" :key="index">
            <el-col :span="4">
              <p v-if="index===0">
                主要旅客
                <i style="margin-left:5px" class="icon" @click="iconDialogVisible=true">?</i>
              </p>
              <p v-else>旅客</p>
              <el-input ref="input" v-model="item.name" placeholder="请输入旅客姓名" />
            </el-col>
            <el-col :span="4">
              <p>证件类型</p>
              <el-select v-model="item.id_type" placeholder="请选择">
                <el-option v-for="(val, key, i) in id_type" :key="i" :label="val" :value="key" />
              </el-select>
            </el-col>
            <el-col :span="4">
              <p>证件号</p>
              <el-input v-if="item.id_type==='Passport'" v-model="item.id_no" placeholder="请输入证件号" />
              <el-input
                v-else
                v-model="item.id_no"
                placeholder="请输入证件号"
                @blur="onInputBlur(item.id_no,index)"
              />
            </el-col>
            <el-col :span="4">
              <p>
                <span v-if="index===0" style="color:red">*</span>手机号
              </p>
              <el-input v-model="item.telephone" placeholder="请输入手机号" />
            </el-col>
            <el-col :span="4">
              <p>旅客票型</p>
              <el-select
                v-model="item.ticketcode"
                filterable
                allow-create
                placeholder="请选择"
                @change="ticketodeChange(index)"
                @keyup.enter.native="addRow(index)"
              >
                <el-option v-for="(val, key, i) in ticketcode" :key="i" :label="val" :value="key" />
              </el-select>
            </el-col>
            <el-col v-if="index===rowLsit.length-1" :span="4">
              <svg-icon v-if="rowLsit.length!==maxQuantity.all" icon-class="+" @click="addRow(index)" />
              <svg-icon v-if="rowLsit.length>1" icon-class="-" @click="reduceRow(index)" />
            </el-col>
          </el-row>
        </div>
      </el-row>
      <!-- 出票 -->
      <img
        v-if="buyStatus==='' || buyStatus==='NORMAL'"
        class="fixed"
        src="@/assets/homepage/tickets.png"
        @click="addTicketDialogVisible=true"
      >
    </div>
    <!-- 出票弹出对话框 -->
    <el-dialog title="提示" :visible.sync="addTicketDialogVisible" width="30%" class="addTicket">
      <p>
        <i>!</i>请确认旅客信息，成功出票将后将对商户资金进行扣款
      </p>
      <div>
        <el-button @click="addTicketDialogVisible=false">取 消</el-button>
        <el-button class="el-button-right" type="primary" :autofocus="true" @click="addTicket">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 提示对话框 -->
    <el-dialog title="提示" :visible.sync="iconDialogVisible" width="30%">
      <span>主要旅客电话号码不能为空</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="iconDialogVisible = false">取 消</el-button>
        <el-button class="el-button-right" type="primary" @click="iconDialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 购票失败 -->
    <fail v-if="buyStatus==='REFUND'" />

    <!-- 等待中 -->
    <awaits
      v-if="buyStatus==='PROCESS'"
      :uid="uid"
      @continueBuying="continueBuying"
      @updataBuyStatus="updataBuyStatus"
      @goBack="goBack"
    />
  </div>
</template>
<script>
import { getTicket } from '@/api/travel'
import { addTicket } from '@/api/order'
import fail from './buyStatus/fail'
import awaits from './buyStatus/await'
import { idAge } from '@/utils/myFunction'
export default {
  name: 'QuarterAndyear',
  components: {
    fail,
    awaits
  },
  data() {
    return {
      buyStatus: '',
      ticketType: null,
      datetime: null,
      addTicketDialogVisible: false,
      iconDialogVisible: false,
      ticketList: [],
      rowLsit: [
        {
          name: '',
          id_type: '',
          id_no: '',
          telephone: '',
          ticketcode: ''
        }
      ],
      // 证件类型
      id_type: {
        Passport: '护照',
        GovernmentId: '身份证'
      },
      // 旅客票型
      ticketcode: {},
      // 最大旅客数
      maxQuantity: {
        all: null
      },
      num: {},
      // 订单号
      uid: '',
      // 判断是否切换年票季票
      judge: ''
    }
  },
  created() {
    this.keyupSubmit()
  },
  mounted() {
    // this.keyDown()
  },
  methods: {
    keyupSubmit() {
      document.onkeyup = (e) => {
        const _key = window.event.keyCode
        const _ctrlKey = window.event.ctrlKey
        if (_key === 13 && this.buyStatus === '' && _ctrlKey) {
          this.addTicketDialogVisible = true
        } else if (_key === 13 && this.addTicketDialogVisible) {
          this.addTicket()
        }
      }
    },
    continueBuying() {
      this.buyStatus = ''
      this.rowLsit = [
        {
          name: '',
          id_type: '',
          id_no: '',
          telephone: '',
          ticketcode: ''
        }
      ]
    },
    goBack() {
      this.buyStatus = ''
      this.ticketType = null
      this.rowLsit = [
        {
          name: '',
          id_type: '',
          id_no: '',
          telephone: '',
          ticketcode: ''
        }
      ]
    },
    updataBuyStatus(data) {
      this.buyStatus = data
      this.ticketType = null
      this.rowLsit = [
        {
          name: '',
          id_type: 'GovernmentId',
          id_no: '',
          telephone: '',
          ticketcode: ''
        }
      ]
    },
    ticketTypeChange() {
      switch (this.ticketType) {
        case 'year':
          this.getTicket({ type: 'YEAR' })
          // if (this.judge === 'season') {
          this.rowLsit.forEach((item) => {
            item.ticketcode = ''
          })
          // }
          // this.judge = 'year'
          break
        case 'season':
          this.getTicket({ type: 'SEASON' })
          // if (this.judge === 'year') {
          this.rowLsit.forEach((item) => {
            item.ticketcode = ''
          })
          // }
          // this.judge = 'season'
          break
      }
    },
    getTicket(type) {
      getTicket(type).then((res) => {
        this.ticketList = res.data.data.products
        this.datetime = res.data.data.dataGetDateTime.replace(' ', 'T')

        this.ticketcode = {}
        for (const key in this.ticketList) {
          this.ticketcode[key] = this.ticketList[key].description
        }
        // 旅客数量
        this.maxQuantity = {
          all: null
        }
        for (const key in this.ticketList) {
          this.maxQuantity[key] = parseInt(this.ticketList[key].maxQuantity)
        }
        this.maxQuantity.all = parseInt(JSON.parse(localStorage.getItem('init')).ticket_max_number)
      })
    },
    // 添加一行
    async addRow(index) {
      //
      if (this.rowLsit.length < this.maxQuantity.all) {
        await this.rowLsit.push({
          name: '',
          id_type: 'GovernmentId',
          id_no: '',
          telephone: '',
          ticketcode: ''
        })
        this.$refs.input[index + 1].focus()
      } else {
        this.$message({
          showClose: true,
          message: '最大购买单位为' + this.maxQuantity.all + '人',
          duration: 3000,
          type: 'warning'
        })
      }
    },
    async reduceRow(index) {
      if (this.rowLsit.length > 1) {
        await this.rowLsit.pop()
        this.$refs.input[index - 1].focus()
      } else {
        this.$refs.input[index].focus()
      }
    },
    // 失去焦点
    onInputBlur(identityCard) {
      const a = idAge(identityCard)
      console.log(a)
    },
    // 监听旅客票型
    ticketodeChange(index) {
      this.num = {}
      for (var key in this.num) {
        delete this.num[key]
      }

      for (const key in this.maxQuantity) {
        this.num[key] = 0
      }
      delete this.num.all

      this.rowLsit.forEach((item) => {
        for (const key in this.num) {
          if (item.ticketcode === key) {
            this.num[key]++
          }
        }
      })

      // 判断是否大于规定人数
      for (const key in this.num) {
        if (this.num[key] > this.maxQuantity[key]) {
          this.changeRepeat(
            index,
            this.maxQuantity[key],
            this.ticketList[key].baseProduct.description
          )
        }
      }
    },
    // 重复代码封装
    changeRepeat(index, number, value) {
      this.$message({
        showClose: true,
        message:
          '已超出可以购买上限，您的' + value + '只能购买' + number + '张',
        duration: 3000,
        type: 'warning'
      })
      this.rowLsit[index].ticketcode = ''
    },
    // 出票
    addTicket() {
      this.addTicketDialogVisible = false
      const data = {
        ticketEntity: [],
        contact: {
          name: '',
          telephone: ''
        }
      }
      // 给contact赋值
      data.contact.name = this.rowLsit[0].name
      data.contact.telephone = this.rowLsit[0].telephone
      // 给ticketEntity赋值
      // for (const key in this.num) {
      //   if (this.num[key] !== 0) {
      //     data.ticketEntity.push(this.addTicketRepeat(key))
      //   }
      // }
      this.rowLsit.forEach(item => {
        if (item.ticketcode !== '') {
          data.ticketEntity.push(this.addTicketRepeat(item.ticketcode))
        }
      })
      // data.ticketEntity.forEach(item => {
      //   item.guest.forEach(i => {
      //     delete i.ticketcode
      //     this.rowLsitticketcode= i.ticketcode
      //   })
      // })
      // console.log(this.rowLsit)
      // console.log(data)
      addTicket(data).then((res) => {
        if (res.data.code === 200) {
          this.buyStatus = res.data.data.status
          this.uid = res.data.data.order_id
          this.$message({
            showClose: true,
            message: '购票成功',
            duration: 3000,
            type: 'success'
          })
          // this.judge = this.ticketType
        }
      })
    },
    // 出票重复代码
    addTicketRepeat(ticketcode) {
      const data_ticket = {
        code: null,
        datetime: null,
        price: null,
        guest: []
      }
      data_ticket.code = this.ticketList[ticketcode].baseProduct.code
      data_ticket.datetime = this.datetime
      data_ticket.price = this.ticketList[
        ticketcode
      ].baseProduct.prices[0].value.toFixed(2)
      const copyList = this.rowLsit.concat()
      //
      copyList.forEach((item) => {
        if (item.ticketcode === ticketcode) {
          data_ticket.guest.push(item)
        }
      })
      //
      // data_ticket.guest.forEach(item => {
      //   delete item.ticketcode
      // })
      return data_ticket
    }
  }
}
</script>
<style lang="scss" scoped>
.content {
  padding: 24px;
  width: 100%;
  div {
    .box-card {
      width: 257px;
      display: inline-block;
      margin-right: 50px;
      .drop {
        margin-bottom: 10px;
      }
    }
  }
  .text_item {
    p {
      .icon {
        display: inline-block;
        width: 12px;
        height: 12px;
        text-align: center;
        border-radius: 50%;
        color: #999999;
        border: 1px solid #999999;
        font-size: 12px;
        cursor: pointer;
      }
    }
    .el-input {
      width: 80%;
    }
    .el-select {
      width: 80%;
    }
    .svg-icon {
      position: absolute;
      font-size: 26px;
      bottom: 5px;
      cursor: pointer;
    }
    .svg-icon:nth-child(2) {
      margin-left: 50px;
    }
  }
  .fixed {
    position: fixed;
    bottom: 27px;
    right: 27px;
  }
  // 出票弹出框
  .addTicket {
    p {
      margin-top: 0px;
      margin-bottom: 30px;
      i {
        text-align: center;
        display: inline-block;
        margin-right: 12px;
        border-radius: 50%;
        width: 18px;
        height: 18px;
        background-color: #e29836;
        color: blanchedalmond;
      }
    }
    div {
      text-align: right;
    }
  }
}
.success {
  // position: relative;
  .svg-icon {
    position: absolute;
    bottom: 0px;
    margin-left: -16px;
  }
  span {
    position: absolute;
    bottom: 3px;
    margin-left: 24px;
    font: 14px;
    color: #3ac23a;
  }
}
</style>
<style>
.el-card__header {
  padding: 24px 24px !important;
}
</style>
